package com.lh.project.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lh.project.common.UserHolder;
import com.lh.project.mapper.VoucherOrderMapper;
import com.lh.project.model.entity.SeckillVoucher;
import com.lh.project.model.entity.VoucherOrder;
import com.lh.project.service.SeckillVoucherService;
import com.lh.project.service.VoucherOrderService;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.aop.framework.AopContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.connection.stream.*;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.time.Duration;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

/**
*
*/
@Service
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder>
implements VoucherOrderService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private RedissonClient redissonClient;
    @Resource
    private SeckillVoucherService seckillVoucherService;


    private static final DefaultRedisScript<Long> SECKILL_SCRIPT;
    static {
        SECKILL_SCRIPT = new DefaultRedisScript<>();
        SECKILL_SCRIPT.setLocation(new ClassPathResource("seckill.lua"));
        SECKILL_SCRIPT.setResultType(Long.class);
    }


    private ExecutorService SECKILL_ORDER_EXECUTOR = Executors.newSingleThreadExecutor();


    /**
     * 改注解可以使下面的方法在类初始化之后，执行
     */
    @PostConstruct
    private void init(){
        SECKILL_ORDER_EXECUTOR.submit(new VoucherOrderHandler());
    }

    private  class VoucherOrderHandler implements Runnable {

        String queueName = "stream.orders";
        @Override
        public void run() {
            while(true){
                try {
                    //1. 获取消息队列中的订单信息XREADGROUP GROUP g1 c1 count 1 Block 2000 STRWAMS stream.orders >
                    List<MapRecord<String, Object, Object>> read = stringRedisTemplate.opsForStream().read(
                            Consumer.from("g1", "c1"),
                            StreamReadOptions.empty().count(1).block(Duration.ofSeconds(2)),
                            StreamOffset.create(queueName, ReadOffset.lastConsumed())
                    );
                    //2. 判断消息获取是否成功

                    if(read == null || read.isEmpty()){

                        //2.1 如果获取失败，说明没有消息，继续下一次循环
                        continue;
                    }

                    //2.2 成功
                    //3. 解析消息中的订单

                    MapRecord<String, Object, Object> record = read.get(0);
                    Map<Object, Object> value = record.getValue();
                    VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(value, new VoucherOrder(), true);
                    //4. 创建订单
                    handleVoucherOrder(voucherOrder);
                    //5. ACK确认 SACK stream.orders g1 id
                    stringRedisTemplate.opsForStream().acknowledge(queueName,"g1",record.getId());
                }catch (Exception e){
                    handlePendingList();
                    log.error("处理订单异常");
                }
            }
        }
        private void handlePendingList(){
            while(true){
                try {
                    //1. 获取pending-list中的订单信息
                    //XREADGROUP GROUP g1 ci COUNT 1 STRWAMS stream.orders 0
                    List<MapRecord<String, Object, Object>> list = stringRedisTemplate.opsForStream().read(
                            Consumer.from("g1", "c1"),
                            StreamReadOptions.empty().count(1),
                            StreamOffset.create(queueName, ReadOffset.from("0"))
                    );
                    //2. 没有读到
                    if (list == null || list.isEmpty()) {
                        //pending-list中没有信息，结束
                        break;
                    }
                    //3. 有，则继续执行
                    MapRecord<String, Object, Object> record = list.get(0);
                    Map<Object, Object> value = record.getValue();
                    VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(value, new VoucherOrder(), true);
                    //4. 生成订单
                    handleVoucherOrder(voucherOrder);
                    //5. 确认
                    stringRedisTemplate.opsForStream().acknowledge(queueName, "g1", record.getId());
                }catch (Exception e){
                    log.error("处理pending-list异常",e);
                    try {
                        Thread.sleep(20);
                    } catch (InterruptedException ex) {
                        ex.printStackTrace();
                    }
                }
            }
        }
    }



    //一下是使用java中自带的工具
    private BlockingQueue<VoucherOrder> orderTasks = new ArrayBlockingQueue<>(1024*1024);
    private class VoucherOrderHandler1 implements Runnable{

        @Override
        public void run() {
            while (true){
                //1. 获取队列中的订单信息
                //获取队列中的头部，如果有需要则等待知道元素可用
                try {
                VoucherOrder voucherOrder = orderTasks.take();
                handleVoucherOrder(voucherOrder);
                }catch (InterruptedException e){
                   log.error("处理订单异常");
                }
                //2. 创建订单

            }
        }
    }

    private void handleVoucherOrder(VoucherOrder voucherOrder) {
        //创建锁对象
        //因为现在是一个多线程，不是主线程，所以如果使用UserHolder获取用户信息是获取不到的
//        Long id = UserHolder.getUser().getId();
        RLock lock = redissonClient.getLock("lock:order:" + voucherOrder.getUserId());
        //判断是否获取锁成功
        if(!lock.tryLock()){
            log.error("不允许重复下单");
            return;
        }
        try {
            proxy.createVoucherOrder(voucherOrder);
        }finally {
            lock.unlock();
        }
    }

    public void createVoucherOrder(VoucherOrder voucherOrder){
        //1. 一人一单
        Long userId = voucherOrder.getVoucherId();
        //1.1 查询订单
        long count = query().eq("user_id",userId)
                .eq("voucher_id",voucherOrder.getVoucherId()).count();
        //1.2 判断订单是否存在
        if(count > 0){
            log.error("用户已经购买过一次了");
            return;
        }
        //2. 扣减库存
        boolean success = seckillVoucherService.update()
                .setSql("stock = stock -1")
                .eq("voucher_id", voucherOrder.getVoucherId())
                .gt("stock", 0)
                .update();
        if (!success) {
            log.error("库存不足");
        }
        //3. 订单写入数据库
        save(voucherOrder);
    }
    private VoucherOrderService proxy;
    @Override
    public String setVoucherOrder(Long id) {

        // 1. 查询优惠券
        SeckillVoucher voucher = seckillVoucherService.getById(id);
        if(voucher==null){
            //表示不存在该优惠券
            return "优惠券不存在";
        }
        //2. 判断段秒杀是否开始
        Date date = new Date();
        if(voucher.getBeginTime().after(date)){
            return "活动未开始";
        }
        if(voucher.getEndTime().before(date)){
            return "秒杀已经结束";
        }

        //1. 执行lua脚本
        Long result = stringRedisTemplate.execute(
                SECKILL_SCRIPT,
                Collections.emptyList(),
                id.toString(),
                UserHolder.getUser().getId().toString()
        );
        //2. 判断结果是否是0
        //2.1 不为0 代表没有购买资格
        int r = result.intValue();
        if(r != 0){
            return r==1?"库存不足":"不能重复下单";
        }
        //3. 获取代理对象
        proxy = (VoucherOrderService)AopContext.currentProxy();
        return "下单成功";
    }






    public String setVoucherOrder2(Long id) {
        //1. 执行lua脚本
        Long result = stringRedisTemplate.execute(
                SECKILL_SCRIPT,
                Collections.emptyList(),
                id.toString(),
                UserHolder.getUser().getId().toString()
        );
        //2. 判断结果是否是0
        //2.1 不为0 代表没有购买资格
        int r = result.intValue();
        if(r != 0){
            return r==1?"库存不足":"不能重复下单";
        }
        //2.2 为0，有购买资格，将下单消息保持到阻塞队列
        //TODO 保持阻塞队列
        VoucherOrder voucherOrder = new VoucherOrder();
        voucherOrder.setUserId(UserHolder.getUser().getId());
        voucherOrder.setVoucherId(id);
        orderTasks.add(voucherOrder);
        //3. 获取代理对象
        proxy = (VoucherOrderService)AopContext.currentProxy();
        return "下单成功";
    }


    public String setVoucherOrder1(Long id) {
        // 1. 查询优惠券
        SeckillVoucher voucher = seckillVoucherService.getById(id);
        if(voucher==null){
            //表示不存在该优惠券
            return "优惠券不存在";
        }
        //2. 判断段秒杀是否开始
        Date date = new Date();
        if(voucher.getBeginTime().after(date)){
            return "活动未开始";
        }
        if(voucher.getEndTime().before(date)){
            return "秒杀已经结束";
        }
        //4. 判断是否充足
        if(voucher.getStock() < 1){
            return "库存不足";
        }

        //创建锁对象
//        SimpleRedisLock lock = new SimpleRedisLock(stringRedisTemplate,"order:" + UserHolder.getUser().getId());
        RLock lock = redissonClient.getLock("order:" + UserHolder.getUser().getId());
        //获取锁
//        boolean isLock= lock.tryLock(5);
        boolean isLock = lock.tryLock();
        //判断是否获取锁成功
        if(!isLock){
            //获取锁失败,返回错误信息
            return "不允许重复下单";
        }

        try {
            VoucherOrderService proxy =(VoucherOrderService) AopContext.currentProxy();
            return proxy.createVoucherOrder(id);
        }finally {
            lock.unlock();
        }

//        synchronized (UserHolder.getUser().getId().toString().intern()) {
//            //拿到代理对象
//            VoucherOrderService proxy =(VoucherOrderService) AopContext.currentProxy();
//
//            return proxy.createVoucherOrder(id);
//        }


    }

    @Transactional
    public String createVoucherOrder(Long id) {
        /*
        单单使用UserHolder.getUser().getId().toString()的话是不行的
        因为每次一来就会建立一个全新的字符串，可以去看源码，所以这个枷锁方式不行
        */
//        synchronized (UserHolder.getUser().getId().toString()) {
        /*
            加入intern()：返回字符串的规范表示。
            最初为空的字符串池由string类私有维护。
            当调用实习生方法时候，如果池中的已经包含了一个等于这个string
            对象（由equals(Object)方法确定)的字符串，则返回池中的字符串，否则
            将由此String对象添加到池中并返回该字符串的引用
            这样可以确保，当用户id一样时，返回的值就是一个
        * */
//        synchronized (UserHolder.getUser().getId().toString().intern()) {
            //5. 一人一单问题
            //5.1 查询订单
            Long count = query().eq("user_id", UserHolder.getUser().getId())
                    .eq("voucher_id", id)
                    .count();
            //5.2 判断是存在
            if (count > 0) {
                //用户已经购买过了
                return "您已经购买过了";
            }

            //6. 扣减库存
            boolean success = seckillVoucherService.update()
                    .setSql("stock = stock -1")
                    .eq("voucher_id", id)
//                .eq("stock",voucher.getStock())
                    .gt("stock", 0)
                    .update();
            if (!success) {
                return "库存不足";
            }
            //7. 创建订单
            VoucherOrder voucherOrder = new VoucherOrder();
            voucherOrder.setUserId(UserHolder.getUser().getId());
            voucherOrder.setVoucherId(id);
            //8. 订单写入数据库
            save(voucherOrder);
            return "抢单成功！";
        }
//    }

}
